//
//  YDNotiViewController.m
//  PeiZiWangBei
//
//  Created by 巨彦新 on 2018/1/18.
//  Copyright © 2018年 LK-IOS. All rights reserved.
//

#import "YDNotiViewController.h"
#import "YDMessageCell.h"
#import "YDNotiModel.h"
#import "YDPositionViewController.h"
#import "YDFundDetailsController.h"
#import "YDBaseOptionsViewController.h"

@interface YDNotiViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableView;

/**
 数据源
 */
@property (nonatomic, strong)NSMutableArray *notiList;
/**
 当前页码
 */
@property (nonatomic , assign) NSInteger currentPage;


/**
 无数据
 */
@property (nonatomic , weak) SYNoDataView *dataView;
@end

@implementation YDNotiViewController

-(NSMutableArray *)notiList
{
    if (_notiList == nil) {
        _notiList = [NSMutableArray new];
    }
    return _notiList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self tableView];
    [self loadData];
    [self setUpDataManger];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}
- (void)removeNodataView
{
    if (_dataView != nil) {
        [_dataView removeFromSuperview];
        _dataView = nil;
    }
}


-(void)setUpDataManger
{
    MJGIFHeader *header = [MJGIFHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    //隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES ;
    //隐藏状态
    header.stateLabel.hidden = YES ;
    self.tableView.mj_header = header;
    
    MJGIFFooter *footer = [MJGIFFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.stateLabel.hidden = YES;
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
    
    
}
- (void)loadData
{
    //type(1:站内消息,2:站外消息)
    
    self.currentPage = 0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(self.currentPage) forKey:@"page"];
    [dict setObject:@(10) forKey:@"size"];
    [dict setObject:@2 forKey:@"type"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:GetMessageList WithSuccessBlock:^(NSDictionary *resultDict) {
        DDLog(@"resultDict = %@" , resultDict)
        [self.tableView.mj_header endRefreshing];
        if ([resultDict[@"code"] integerValue] == 200) {
            [self.notiList removeAllObjects];
            self.notiList = [YDNotiModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            
            if (self.notiList.count < 10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
            }
            
            [self.tableView reloadData];
            
            
            if (self.notiList.count) {
                [self removeNodataView];
                
            }else
            {
                [self dataView];
                
            }
        }
        else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        DDLog(@"error = %@" , error)
        [self.tableView.mj_header endRefreshing];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:YES];
    }];
}

-(void)loadMoreData
{
    self.currentPage++;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(self.currentPage) forKey:@"page"];
    [dict setObject:@(10) forKey:@"size"];
    [dict setObject:@2 forKey:@"type"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:GetMessageList WithSuccessBlock:^(NSDictionary *resultDict) {
        
        [self.tableView.mj_footer endRefreshing];
        if ([resultDict[@"code"] integerValue] == 200) {
            
            NSArray *newsArr =  [YDNotiModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            [self.notiList addObjectsFromArray:newsArr];
            
            if (newsArr.count < 10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshing];
            }
            [self.tableView reloadData];
            
            
        }
        else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:YES];
            
        }
    } failBlock:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:YES];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.notiList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDMessageCell *cell = [YDMessageCell cellWithTbaleview:tableView];
    cell.model = [self.notiList objectAtIndex:indexPath.row];
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.notiList.count) {
        return [YDMessageCell heightForCellWithModel:[self.notiList objectAtIndex:indexPath.row]];
    }else
    {
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDNotiModel *model = [self.notiList objectAtIndex:indexPath.row];
    [self dealWithTapWithModel:model];
}

- (void)dealWithTapWithModel:(YDNotiModel *)model
{
    
    //    PZBaseOptionsViewController *vc = [[PZBaseOptionsViewController alloc] init];
    //    vc.optionsType = InOptions;
    //    vc.hidesBottomBarWhenPushed = YES;
    //    [self.navigationController pushViewController:vc animated:YES];
    //    return;
    
    if ([model.outsideMsgType isEqualToString:@"OPTION_WAITCONFIRMED"]||
        [model.outsideMsgType isEqualToString:@"OPTION_INSETTLEMENT"] ||
        [model.outsideMsgType isEqualToString:@"OPTION_TURNOVER"]) {
        //期权 持仓
        YDBaseOptionsViewController *vc = [[YDBaseOptionsViewController alloc] init];
        vc.optionsType = InOptions;
        vc.isHiddenTabbar = YES;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    else if([model.outsideMsgType isEqualToString:@"OPTION_SETTLEMENTED"] ||
            [model.outsideMsgType isEqualToString:@"OPTION_FAILURE"])
    {
        //期权 结算
        YDBaseOptionsViewController *vc = [[YDBaseOptionsViewController alloc] init];
        vc.optionsType = OutOptions;
        vc.hidesBottomBarWhenPushed = YES;
        vc.isHiddenTabbar = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if ([model.outsideMsgType isEqualToString:@"BUY_UNWIND"] ||
             [model.outsideMsgType isEqualToString:@"BUY_SELLFAILED"]||
             [model.outsideMsgType isEqualToString:@"BUY_BUYFAILED"]) {
        //跳转结算 卖出失败 买入失败 已平仓
//        YDPositionViewController *vc = [[YDPositionViewController alloc] init];
//        vc.isHiddenTabbar = YES;
//        vc.deafaultIndex = 2;
//        [self.navigationController pushViewController:vc animated:YES];
    }
    else if ([model.outsideMsgType isEqualToString:@"ACCOUNT_RECHARGESUCCESS"] ||
             [model.outsideMsgType isEqualToString:@"ACCOUNT_WITHDRAWALSSUCCESS"] ||
             [model.outsideMsgType isEqualToString:@"ACCOUNT_WITHDRAWALFAILED"])
    {
        //跳转资金明细
        //资金明细
        YDFundDetailsController *vc = [[YDFundDetailsController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else
    {
        //跳转持仓
//        YDPositionViewController *vc = [[YDPositionViewController alloc] init];
//        vc.isHiddenTabbar = YES;
//        vc.deafaultIndex = 1;
//        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
    [self requestReadMessageWithModel:model];
}
/**
 已读消息
 */
- (void)requestReadMessageWithModel:(YDNotiModel*)model
{
    // /messaging/read/{id}
    
    NSString *url = [NSString stringWithFormat:@"%@%@",@"/messaging/read/" , model.ID];
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:POSTMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        
        DDLog(@"resultDict = %@" , resultDict)
        if ([resultDict[@"code"] integerValue] == 200) {
            [self loadData];
        }
    } failBlock:^(NSError *error) {
        
    }];
}

/*******tableView********/
-(UITableView *)tableView
{
    if (_tableView == nil) {
        CGFloat safeTopH = isPhoneX ? 84 : 64;
        CGFloat safeBottomH = isPhoneX ? 34 : 0;
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, LKScreenH - safeTopH - safeBottomH) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = [UIColor colorWithHexString:mainGray];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // tableView.contentInset = UIEdgeInsetsMake(0, rate375(7),0, rate375(7));
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.showsVerticalScrollIndicator = NO;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.tableFooterView = [UIView new];
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}
/*******dataView********/
-(SYNoDataView *)dataView
{
    if (_dataView == nil) {
        CGFloat dataW = rate375(240);
        CGFloat dataX = (LKScreenW - dataW) * 0.5;
        CGFloat dataH = isPhoneX ? rateX812(196) : rate750(196);
        CGFloat dataY = isPhoneX ? rateX812(132) : rate750(132);
        CGRect frame = CGRectMake(dataX, dataY, dataW, dataH);
        //wuneirong   wuxinhao
        SYNoDataView *dataView = [SYNoDataView positionNoDataViewInitWithFrame:frame ImageString:@"wuneirong" buttonTitle:@"" IsCanSeeBuyButton:NO];
        [self.tableView addSubview:dataView];
        _dataView = dataView;
    }
    return _dataView;
}
@end
